package com.winit.schedule.job.tracker.repository.mysql.type.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.util.StringUtils;

@MappedTypes({ Set.class })
@MappedJdbcTypes({ JdbcType.VARCHAR })
public class SetTypeHandler implements TypeHandler<Set<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, Set<String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, StringUtils.collectionToDelimitedString(parameter, ","));
    }

    @Override
    public Set<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return string2set(value);
    }

    @Override
    public Set<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return string2set(value);
    }

    @Override
    public Set<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return string2set(value);
    }

    private Set<String> string2set(String value) {
        if (null != value) {
            return StringUtils.commaDelimitedListToSet(value);
        } else {
            return new HashSet<String>();
        }
    }

}
